package com.test.demo.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.test.demo.common.Constants;
import com.test.demo.common.result.Result;
import com.test.demo.utils.NetworkUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "发送短信接口")
@RequestMapping("/sms")
@Slf4j
public class SmsController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private HttpServletRequest request;

    @GetMapping("getAuthCodeImg")
    @ApiOperation("图形验证码")
    public void getAuthCodeImg(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //定义图形验证码的长和宽  码值个数  干扰圈数
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(90, 40, 4, 2);
        BufferedImage codeImg = circleCaptcha.getImage();
        String code = circleCaptcha.getCode();
        String ipAddress = NetworkUtil.getIpAddress(request);
        redisTemplate.opsForValue().set(Constants.IMG_IDENTIFY_CODE + ipAddress, code,5, TimeUnit.MINUTES);
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(codeImg, "jpeg", sos);
    }

    @PostMapping("/sendSms")
    @ApiOperation("发送短信")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, paramType = "form"),
            @ApiImplicitParam(name = "imgCode", value = "图形验证码", paramType = "form"),
    })
    public Result add(String mobile, String imgCode) {
        if (StringUtils.isBlank(mobile)) {
            return Result.fail("手机号不允许为空");
        }
        String ipAddress = NetworkUtil.getIpAddress(request);
        if (StringUtils.isNotBlank(imgCode)) {
            String imgOldCode = (String) redisTemplate.opsForValue().get(Constants.IMG_IDENTIFY_CODE + ipAddress);
            if (!imgCode.equals(imgOldCode)) {
                return Result.fail("图形验证码不正确");
            }
            redisTemplate.delete(Constants.IMG_IDENTIFY_CODE + ipAddress);
        }
        Long ipCount = redisTemplate.opsForValue().increment(Constants.SMS_COUNT.concat(ipAddress), 1);
        if (ipCount == 1) {
            redisTemplate.expire(Constants.SMS_COUNT.concat(ipAddress), 30, TimeUnit.MINUTES);
        }
        if (ipCount > 10) {
            log.info("发送短信ip超过限制:{}", ipAddress);
            return Result.fail("验证码发送频繁,超过了限定的次数,请半小时后再试！");
        }
        Long count = redisTemplate.opsForValue().increment(Constants.SMS_COUNT.concat(mobile), 1);
        if (count == 1) {
            redisTemplate.expire(Constants.SMS_COUNT.concat(mobile),30, TimeUnit.MINUTES);
        }
        if (count > 5) {
            return Result.fail("验证码发送频繁,超过了限定的次数，请半小时后再试！");
        }
        // TODO: 2020/4/17  发送短信
        return Result.success();
    }

}
